/*
 * @Author: wuzhen
 * @Date: 2019-01-22 11:01:48
 * @LastEditors  : wuzhen
 * @LastEditTime : 2019-12-28 16:15:04
 * @Description: 导航菜单
 */

import { asyncRoutes } from "@/router";
// 获取store
import store from "@/store";
/**
 * @description: 判断是否有路由权限
 * @param {roles}
 * @return: true/false
 */
function hasPermission(roles, route) {
  const access = route.meta.access;
  if (store.state.user.userInfo.super_admin) {
    return true;
  } else if (access) {
    return (
      roles.find(item => access.includes(item)) &&
      !access.includes("admin-permission")
    );
  } else {
    return false;
  }
}
/**
 * @description:
 * @param {routes}
 * @param {roles}
 * @return:
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];
  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });
  return res;
}
// 序列化菜单
export function fetchAsyncRoutes(routes, roles) {
  const res = [];
  routes.forEach(route => {
    const tmp = { ...route };
    if (tmp.children) {
      tmp.children = fetchAsyncRoutes(tmp.children, roles);
    }
    res.push(tmp);
  });
  return res;
}

const nav = {
  state: {
    menus: [],
    parentRouter: null
  },
  mutations: {
    set_menus: (state, data) => {
      state.menus = data;
    },
    set_parentRouter: (state, data) => {
      state.parentRouter = data;
    }
  },
  actions: {
    // 获取所有路由菜单
    getMenus({ commit }) {
      return new Promise(resolve => {
        let Routes;
        store.dispatch("GetUserInfo").then(roles => {
          Routes = fetchAsyncRoutes(asyncRoutes, roles);
          commit("set_navList", Routes);
          resolve(Routes);
        });
      });
    },
    // 保存路由地址
    setParentRouter({ commit }, routePath) {
      commit("set_parentRouter", routePath);
    }
  }
};

export default nav;
